<?php /** @noinspection ALL */
/** @noinspection PhpUndefinedClassInspection */

/**
 * @link https://www.len168.com
 * @copyright Copyright (c) 2020-6-10 len168.com
 * @author toshcn <toshcn@foxmail.com>
 */

namespace api\modules\backend\controllers;

use common\models\Menu;
use Yii;
use api\controllers\AuthAdminController;

/**
 * 后台菜单接口 controller for the `backend` module
 */
class MenuController extends AuthAdminController
{
    /**
     * 获取列表
     * @return mixed
     */
    public function actionList()
    {
        try {
            $data = Menu::getAllMenuData(true);
            return Yii::$app->api->success(['items' => $data]);
        } catch (\Exception $e) {
            return Yii::$app->api->success([]);
        }
    }

    /**
     * 创建菜单
     * @return mixed
     * @throws \Exception
     */
    public function actionCreate()
    {
        $this->validateIsPost();
        try {
            $menu = new Menu();
            $data = Yii::$app->getRequest()->post();
            $data['parent_id'] = is_array($data['parent_id']) ? (int)$data['parent_id'][count($data['parent_id']) - 1] : $data['parent_id'];
            if ($menu->load($data, '') && $menu->create()) {
                return Yii::$app->api->success($menu);
            }
            if ($menu->hasErrors()) {
                return Yii::$app->api->error($menu->getFirstErrorMessage());
            }
        } catch (\Exception $e) {
            return Yii::$app->api->error($e->getMessage());
        }
        return Yii::$app->api->error('创建失败');
    }

    /**
     * 更新菜单
     * @return mixed
     * @throws \Exception
     */
    public function actionUpdate()
    {
        $this->validateIsPost();
        $id = (int) Yii::$app->getRequest()->post('id');
        try {
            $menu = Menu::findOne($id);
            $parent = $menu->parent_id;
            $data = Yii::$app->getRequest()->post();
            $data['parent_id'] = is_array($data['parent_id']) ? (int) $data['parent_id'][count($data['parent_id']) - 1] : $data['parent_id'];
            if ($menu->load($data, '') && $menu->updateRow($parent)) {
                return Yii::$app->api->success('更新成功');
            }
            if ($menu->hasErrors()) {
                return Yii::$app->api->error($menu->getFirstErrorMessage());
            }
        } catch (\Exception $e) {
            return Yii::$app->api->error($e->getMessage());
        }
        return Yii::$app->api->error('更新失败');
    }
}
